//
//  UserMapView.m
//  xiaorizi
//
//  Created by kun on 15/11/1.
//  Copyright © 2015年 origin. All rights reserved.
//

#import "UserMapView.h"
#import "KZAnnotation.h"
#import "EveryDayModel.h"
#import "UIImageView+WebCache.h"
#import "Masonry.h"
#import "UIViewAdditions.h"
#import "KZEventAnnotation.h"

#import <objc/runtime.h>

#define WIDTH     [UIScreen mainScreen].bounds.size.width

static char annStoreKey;

@interface UserMapView ()<MKMapViewDelegate,UIScrollViewDelegate>

//定义一个地址编码器 用来进行 地理位置与经纬度坐标的转换
@property (nonatomic,strong) CLGeocoder *geocoder;
@property (nonatomic,assign)BOOL isUserUpdatasLocations;
@property (weak, nonatomic) IBOutlet UIImageView *didianView;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

//记录当前位置
@property (nonatomic,strong) MKUserLocation * userLocation;

//

@property (nonatomic,strong)NSMutableArray *imgViewArray;

@end

@implementation UserMapView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

+(UserMapView *)userMapView
{
    NSString *className = NSStringFromClass([self class]);
    return [[[NSBundle mainBundle]loadNibNamed:className owner:self options:nil]lastObject];
}



-(void)awakeFromNib
{
    //设置地图配置
    
    //默认设置 定位 scrollView是隐藏;
    _mapView.showsUserLocation = YES;
    self.mapView.delegate = self;
    self.mapView.mapType = MKMapTypeStandard;
    
    //添加scrollView代理
    self.scrollView.delegate = self;
    
    //添加地点定位手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dealLocationPoint:)];
    [_didianView addGestureRecognizer:tap];
    
    //开启定位跟踪  一直出问题的地方？
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //初始化数组
    _imgViewArray = [NSMutableArray array];
    
}


//添加自身定位
-(void)dealLocationPoint:(UITapGestureRecognizer *)tap
{
    
    [UIView animateWithDuration:0.5 animations:^{
       self.mapView.centerCoordinate = _userLocation.location.coordinate;
    }];
    
}


-(void)setModel:(EveryDayModel *)model
{
    //添加大头针
//    EveryDayModel *model = dataArray[0];
    self.scrollView.hidden = YES;
    self.didianView.hidden = YES;
    
    NSArray *array = [model.position componentsSeparatedByString:@","];
    CLLocationDegrees latitude  = [array[1] doubleValue];
    CLLocationDegrees longitude = [array[0] doubleValue];
    
    KZEventAnnotation *annotation = [[KZEventAnnotation alloc]init];
    annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
    annotation.title = model.title;
    annotation.image = [UIImage imageNamed:@"zuobiao1"];
    [_mapView addAnnotation:annotation];
}


//填充数据 加载大头针
-(void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;
    
    //做个深拷贝
    NSMutableArray *backDataArray = [self.dataArray mutableCopy];
    //1 循环添加大头针
    [self addAnnotationWithData:backDataArray];
    
    
    //2添加循环滚动的视图
    
    for(int i = 0; i < self.dataArray.count; i ++)
    {
        //获取数据 并显示大头针
        EveryDayModel * model = self.dataArray[i];
        UIImageView *imageV = [[UIImageView alloc]init];
        [imageV sd_setImageWithURL:[NSURL URLWithString:model.imgs]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dealimgViewClicked:)];
        [imageV addGestureRecognizer:tap];
        imageV.tag = i;
        [self.scrollView addSubview:imageV];
        
        [_imgViewArray addObject:imageV];
        
    }
    
    //循环添加到scroolView中
    for(int i = 0; i < _imgViewArray.count; i++)
    {
        UIImageView    * indicatorView = _imgViewArray[i];
        UIImageView    * lastView = i==0? nil : _imgViewArray[i-1];
        if(!lastView)
        {
            [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(@(0));
                make.left.equalTo(@(0));
                make.width.equalTo(@(WIDTH - 47));
                make.height.equalTo(@(self.scrollView.height));
            }];
        }
        else{
            [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lastView.mas_top);
                make.left.equalTo(lastView.mas_right).offset(15);
                make.width.equalTo(@(WIDTH -47));
                make.height.equalTo(@(self.scrollView.height));
            }];
        }
    }
    //设置scrollView大小
    self.scrollView.contentSize = CGSizeMake(((WIDTH -47)*_imgViewArray.count - 15), 0);
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
}

- (void)dealimgViewClicked:(UITapGestureRecognizer *)tap
{
    //处理点击事件
    NSLog(@"--->处理按键点击");
}


//循环添加大头针
-(void)addAnnotationWithData:(NSMutableArray *)dataArray
{
    
    if(dataArray.count == 0)
    {
        return;
    }
    //添加大头针
    EveryDayModel *model = dataArray[0];
    NSArray *array = [model.position componentsSeparatedByString:@","];
    CLLocationDegrees latitude  = [array[1] doubleValue];
    CLLocationDegrees longitude = [array[0] doubleValue];
    
    KZAnnotation *annotation = [[KZAnnotation alloc]init];
    annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
    annotation.title = model.title;
    annotation.image = [UIImage imageNamed:@"zuobiao1"];
    [_mapView addAnnotation:annotation];
    
    [dataArray removeObject:model];
    [self addAnnotationWithData:dataArray];
}


-(void)mapViewWillStartLoadingMap:(MKMapView *)mapView
{
    NSLog(@"---->开始加载地图");
}


//滑动实现 地图跟踪



-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
  //  NSLog(@"--->%lu--->%lf,offsetX : %lf",(long)pageNum,WIDTH,self.scrollView.contentOffset.x);
//
//    [self.scrollView scrollRectToVisible:CGRectMake(pageNum*(WIDTH - 47),self.scrollView.height, WIDTH- 47, self.scrollView.height) animated:YES];

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger pageNum =  scrollView.contentOffset.x/(WIDTH -47);
//
//    self.scrollView.contentOffset = CGPointMake(pageNum*(WIDTH - 32), 0);
//    
    

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    
    if(!_isUserUpdatasLocations)
    {
        //设置中心点
        _userLocation = userLocation;
        
        CLLocationCoordinate2D center = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
        
        //2 设置中心点得区域显示范围
        MKCoordinateSpan span;
        span.latitudeDelta = 0.1;
        span.longitudeDelta = 0.1;
        
        //设置地图区域显示
        MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
        [self.mapView setRegion:region animated:YES];
    }
}


//添加大头针定位

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    NSLog(@"--->添加大头针");
    //判断大头针的类型
    if([annotation isMemberOfClass:[KZAnnotation class]])
    {
        static NSString *key = @"KZAnnotation";
        MKAnnotationView *annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:key];
        
        if(!annotationView)
        {
            annotationView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key];
            
            annotationView.canShowCallout = YES;
            annotationView.calloutOffset = CGPointMake(0, 1);
        }
        //因为大头针是复用 所以这里需要重新复制
        annotationView.annotation = annotation;
        annotationView.image = ((KZAnnotation *)annotation).image;
        
        return annotationView;
    }
    //用于导航定位的大头针显示
    else if([annotation isMemberOfClass:[KZEventAnnotation class]])
    {
        //创建大头针显示
        static NSString *key = @"KZEventAnnotation";
        MKAnnotationView *view = [_mapView dequeueReusableAnnotationViewWithIdentifier:key];
        
        if(!view)
        {
            view = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key];
            view.canShowCallout = YES;
            //设置偏移
            //view.calloutOffset = CGPointMake(0, 1);
            
            //设置右边导航显示
            UIImageView *rightView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"daohang"]];
            rightView.frame = CGRectMake(0, 0, 40, 30);
            view.rightCalloutAccessoryView = rightView;
            
            rightView.userInteractionEnabled = YES;
            
            //添加点击事件
            UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(navi2:)];
            [rightView addGestureRecognizer:gesture];
            
        }
        view.annotation = annotation;
        view.image = ((KZEventAnnotation *)annotation).image;
        
        UIImageView * rightView = (UIImageView *)view.rightCalloutAccessoryView;
        
        //设置关联
        objc_setAssociatedObject(rightView, &annStoreKey, annotation, OBJC_ASSOCIATION_ASSIGN);
    
        return view;
        
    }
    //用于系统大头针的显示
    else{
        MKAnnotationView *annotationView = [[MKAnnotationView alloc]init];
        annotationView.annotation = annotation;
        annotationView.image = [UIImage imageNamed:@"didian"];
        return annotationView;
    }

    return nil;
}



//
- (void) navi2:(UITapGestureRecognizer *)gesture
{
    KZEventAnnotation * ann = objc_getAssociatedObject(gesture.view, &annStoreKey);

    MKMapItem * fromItem = [MKMapItem mapItemForCurrentLocation];
    MKMapItem * toItem = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:ann.coordinate addressDictionary:nil]];

    
    toItem.name = ann.title;
    
    [MKMapItem openMapsWithItems:@[fromItem, toItem]
                   launchOptions:[NSDictionary dictionaryWithObjects:@[MKLaunchOptionsDirectionsModeDriving, @(YES)]
                                                             forKeys:@[MKLaunchOptionsDirectionsModeKey, MKLaunchOptionsShowsTrafficKey]]];

}




@end
